package com.tairanchina.md.meeting.resource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.tairanchina.md.constants.CommonConstants;
import com.tairanchina.md.elife.rabbit.constants.ConnConstants;
import com.tairanchina.md.meeting.constants.BaseRes;
import com.tairanchina.md.meeting.constants.MeetingConstants;
import com.tairanchina.md.meeting.constants.MeetingErrorCode;
import com.tairanchina.md.meeting.constants.MeetingProvider;
import com.tairanchina.md.meeting.dto.AwarderDto;
import com.tairanchina.md.meeting.dto.BaseDto;
import com.tairanchina.md.meeting.dto.Prize;
import com.tairanchina.md.meeting.dto.PrizeDto;
import com.tairanchina.md.meeting.entity.YearMeetingAwarder;
import com.tairanchina.md.meeting.entity.YearMeetingAwardgoods;
import com.tairanchina.md.meeting.entity.YearMeetingUser;
import com.tairanchina.md.meeting.utils.CommonConvertUtil;
import com.tairanchina.md.meeting.utils.GetAwardUtil;
import com.tairanchina.md.turntable.dto.YearMeetingLotteryDto;
import com.tairanchina.txRestFilter.engine.jersey.TxJerseyTools;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.*;

import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 奖品模块
 */
@Path(MeetingConstants.PathRoute.PRIZE_ROOT)
public class PrizeResource
{
	
	Logger logger = LoggerFactory.getLogger(PrizeResource.class);
	private static YearMeetingLotteryDto lotteryDto;
	private static YearMeetingAwarder awarderLocal;
	private static YearMeetingUser userLocal;
	private static YearMeetingAwardgoods awardgoodsLocal;

    /**
     * 根据奖品等级获取奖品列表
     * @return
     */
    @GET
    public Response prizelist(@QueryParam("awardLevel") Integer awardLevel)
    {
    	logger.info("++++++++++++++++++++年会查询奖品+++++++++++++++++++++");

		long time = System.currentTimeMillis();
	/*	if(time < MeetingConstants.MEETING_STARTTIME && time > MeetingConstants.MEETING_ENDTIME){
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("message","年会时间未到，不能抽奖");
			return TxJerseyTools.returnAbort();
		}*/
    	List<YearMeetingAwardgoods> list = new ArrayList<>();
		List<Prize> prizes = new ArrayList<>();
    	BaseDto base = new BaseDto();
    	try {
    		
    		list = MeetingProvider.awardGoodsService.allPrizesByLevel(awardLevel);
			prizes = awardSurplusNumHandle(list);
    		base.setList(prizes);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("年会查询奖品异常",e); 
		}
    	
        /**
         * 类实现描述： 获取奖品列表, 包括奖品数量 名称
         * hzyjie 16/12/24 11:44
         */
        return TxJerseyTools.returnSuccess(JSONObject.toJSONString(base));
    }

    /**
     * 当剩余的奖品数量小于0时，返回数据为0
     * @param list
     * @return
     */
    private List<Prize> awardSurplusNumHandle(List<YearMeetingAwardgoods> list) {

		List<Prize> prizes = new ArrayList<>();
    	for(int i=0;i<list.size();i++){
    		YearMeetingAwardgoods yearMeetingAwardgoods = list.get(i);
			Prize prize = CommonConvertUtil.convert(yearMeetingAwardgoods,new Prize());
			prize.setDrawNum(prize.getAwardNum()-prize.getAwardSurplusNum());
    		if(yearMeetingAwardgoods.getAwardSurplusNum() < 0){
    			yearMeetingAwardgoods.setAwardSurplusNum(0);
    		}
			prize.setAwardSurplusNum(yearMeetingAwardgoods.getAwardSurplusNum());
			prizes.add(prize);
    	}
		return prizes;
	}

	/**
	 * 年终抽奖
	 * @param prizeLevel
	 * @return
	 */
	@GET
    @Path(MeetingConstants.PathRoute.PRIZE_RANDOM)
    public Response prizeRandom(@PathParam("prizeLevel") Integer prizeLevel)
    {
        /**
         * 类实现描述： 抽奖动作, 返回中奖人信息, 请求参数中为奖品等级,
         * hzyjie 16/12/24 11:44
         */
		BaseRes baseRes = new BaseRes();

		PrizeDto prizeDto = new PrizeDto();
		System.out.println("开始抽奖了--------------------------------");

		long start = System.currentTimeMillis();
		System.out.println("当前时间的毫秒值"+start);
		System.out.println("上一次抽奖的时间："+MeetingConstants.LAST_TIME);
		System.out.println("抽奖的时间间隔："+   ((MeetingConstants.LAST_TIME!=null)?(start - MeetingConstants.LAST_TIME):start));
    	if(MeetingConstants.LAST_TIME != null && (start - MeetingConstants.LAST_TIME) < MeetingConstants.INTERVAL){
			baseRes.setCode(Integer.valueOf(MeetingErrorCode.LOTTERY_TOO_FAST.getErrorCode()));
			baseRes.setDescription(MeetingErrorCode.LOTTERY_TOO_FAST.getMessage());
    		return TxJerseyTools.returnAbort(JSON.toJSONString(baseRes));
    	}
    	
    	MeetingConstants.LAST_TIME = start;
    	List<YearMeetingUser> list = new ArrayList<>();
    	YearMeetingUser yearMeetingUser = new YearMeetingUser();
    	YearMeetingAwarder awarder = new YearMeetingAwarder();
    	try {
    		list = MeetingProvider.userService.findAllPrizeUser();
    		if(list != null && !list.isEmpty()){
    			
    			//抽奖，返回中奖的用户信息
    			yearMeetingUser = GetAwardUtil.luckPrize(list);

				if(yearMeetingUser != null){

					YearMeetingUser user = new YearMeetingUser();
					user.setId(yearMeetingUser.getId());
					user.setIsAward(MeetingConstants.COMMON_ONE);
					userLocal = user;

					prizeDto.setDepartment(yearMeetingUser.getDepartment());
					prizeDto.setName(yearMeetingUser.getUserName());
					prizeDto.setUserPic(yearMeetingUser.getUserPic());
					prizeDto.setCompany(yearMeetingUser.getCompany());
					prizeDto.setUserPhone(yearMeetingUser.getUserPhone());

					//根据奖品级别查询奖品信息
					YearMeetingAwardgoods goods = MeetingProvider.awardGoodsService.findGoodsByLevel(prizeLevel);
					prizeDto.setAwardPic(goods.getAwardPic());
					prizeDto.setPrizeName(goods.getAwardName());
					int prizeNum = goods.getAwardSurplusNum();
					if(prizeNum >= 1){
						prizeDto.setPrizeNum(prizeNum - 1);
					}else{
						prizeDto.setPrizeNum(0);
					}
					prizeDto.setAwardNum(goods.getAwardNum());
					prizeDto.setDrawNum(goods.getAwardNum()-goods.getAwardSurplusNum()+1);

					//记录中奖信息
					setAwarder(prizeLevel, yearMeetingUser, awarder, goods);
					awarderLocal = awarder;

					YearMeetingAwardgoods gg = new YearMeetingAwardgoods();
					gg.setId(goods.getId());
					gg.setAwardSurplusNum(goods.getAwardSurplusNum()-1);

					awardgoodsLocal = gg;


					//保存用户中奖信息
					lotteryDto = new YearMeetingLotteryDto();
					lotteryDto.setAwardLevel(prizeLevel);
					lotteryDto.setAwardState(true);
					lotteryDto.setUserPhone(yearMeetingUser.getUserPhone());

				}
    		}
    		
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("年会抽奖异常：",e);
			baseRes.setCode(Integer.valueOf(MeetingErrorCode.LOTTERY_ERROR.getErrorCode()));
			baseRes.setDescription(MeetingErrorCode.LOTTERY_ERROR.getMessage());
			return TxJerseyTools.returnAbort(JSON.toJSONString(baseRes));
		}
        return TxJerseyTools.returnSuccess(JSONObject.toJSONString(prizeDto));
    }
	/**
	 * 将最新的中奖信息发送到阿里云
	 * @return
	 */
	@PUT
	public Response sendPrizeMsg()
	{
		logger.info("++++++++++++++++++++年会发送中奖信息+++++++++++++++++++++");

		try {
			if(lotteryDto != null){
				//修改奖品剩余数量
				MeetingProvider.awardGoodsService.updateGoodsByIdForNum(awardgoodsLocal);

				//修改用户的中奖状态
				MeetingProvider.userService.updateUser(userLocal);
				userLocal = null;

				//保存中奖信息
				MeetingProvider.awarderService.addAwarder(awarderLocal);
				awarderLocal = null;
				ConnConstants.getProducerClient().sendMessage(MeetingConstants.EXCHANGE_NAME_YEAR_LOTTERY,MeetingConstants.QUEUE_KEY_YEAR_LOTTERY,lotteryDto);
				lotteryDto = null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("年会发送最新中奖信息失败",e);

			return TxJerseyTools.returnAbort(CommonConstants.ErrorCode.ERROR_SERVICE_IN_REST);
		}

		return TxJerseyTools.returnSuccess();
	}
	/**
	 * 填充中奖信息，记录数据库
	 * @param prizeLevel
	 * @param yearMeetingUser
	 * @param awarder
	 * @param goods
	 */
	private void setAwarder(Integer prizeLevel, YearMeetingUser yearMeetingUser, YearMeetingAwarder awarder,
			YearMeetingAwardgoods goods) {
		awarder.setAwardLevel(prizeLevel);
		awarder.setAwardName(goods.getAwardName());
		awarder.setDepartment(yearMeetingUser.getDepartment());
		awarder.setUserPhone(yearMeetingUser.getUserPhone());
		awarder.setUserName(yearMeetingUser.getUserName());
		awarder.setCompany(yearMeetingUser.getCompany());
		awarder.setUserPic(yearMeetingUser.getUserPic());
	}
}
